package base.engine;

import java.util.ArrayList;
import java.util.HashMap;

import base.Start;
import base.common.IGui;
import base.common.IHandler;
import base.common.IInput;
import base.common.IRender;
import base.render.RenderEntityMissing;

import com.living.Block;
import com.living.EntityPlayer;
import com.render.RenderBlock;
import com.render.RenderPlayer;

public class RenderHandler implements IHandler
{
	private static HashMap<Class<?>, IRender> renderMapping = new HashMap<Class<?>, IRender>();

	private ArrayList<IGui> initList = new ArrayList<IGui>();

	/**List of gui on screen*/
	public ArrayList<IGui> guiList = new ArrayList<IGui>();

	private int updateTick;
	private static final int TICKS_PER_UPDATE = 4;

	public RenderHandler()
	{
		registerRenderToMap(null, (IRender) new RenderEntityMissing());
		
		registerRenderToMap(EntityPlayer.class, (IRender) new RenderPlayer());
		registerRenderToMap(Block.class, (IRender) new RenderBlock());
	}

	/**Get render for class from mapping*/
	public static IRender getRenderFromMap(Class<?> par1Class)
	{
		return renderMapping.get(par1Class);
	}

	/**Register class to render for mapping; if duplicate, will overwrite*/
	public static void registerRenderToMap(Class<?> par1Class, IRender par2IRender)
	{
		renderMapping.put(par1Class, par2IRender);
	}

	@Override
	public void initiate() {}

	@Override
	public void update()
	{
		for (IGui igui : this.initList)
		{
			igui.onInit();
			this.guiList.add(igui);
		}

		this.initList.clear();

		Start.worldManager.render();

		if (this.updateTick++ > TICKS_PER_UPDATE)
		{
			this.updateTick = 0;

			for (IGui igui : this.guiList)
			{
				igui.onUpdate();
			}
		}

		for (IGui igui : this.guiList)
		{
			igui.onRender();
		}
	}

	@Override
	public void terminate()
	{
		this.initList.clear();
		this.guiList.clear();
	}

	public IGui addGui(IGui par1IGui)
	{
		this.initList.add(par1IGui);
		if (par1IGui instanceof IInput)
		{
			Start.inputManager.registerInput((IInput) par1IGui);
		}

		return par1IGui;
	}
}
